import { ref, computed } from 'vue';
import { getReviewsByMerchant } from '@/api/review';

export interface Review {
  id: number;
  customerName: string;
  customerAvatar: string;
  score: number;
  content: string;
  images: string[];
  replyContent?: string;
  createTime: string;
}

export interface ReviewStats {
  averageScore: number;
  totalCount: number;
  goodCount: number;
  mediumCount: number;
  badCount: number;
}

export function useReviews() {
  const reviews = ref<Review[]>([]);
  const reviewStats = ref<ReviewStats>({
    averageScore: 0,
    totalCount: 0,
    goodCount: 0,
    mediumCount: 0,
    badCount: 0
  });

  // 加载评价列表
  const loadReviews = async (merchantId: number, defaultRating: number = 4.8) => {
    try {
      const result: any = await getReviewsByMerchant(
        merchantId.toString(),
        1,
        20
      );
      
      if (result && result.rows) {
        reviews.value = result.rows.map((r: any) => ({
          id: r.reviewId,
          customerName: r.customerNickname || '匿名用户',
          customerAvatar: r.customerAvatarUrl || '/static/logo.png',
          score: r.score,
          content: r.content,
          images: r.images ? JSON.parse(r.images) : [],
          replyContent: r.replyContent,
          createTime: r.createdAt
        }));
        
        // 计算评价统计
        reviewStats.value.totalCount = result.total || reviews.value.length;
        reviewStats.value.goodCount = reviews.value.filter(r => r.score >= 4).length;
        reviewStats.value.mediumCount = reviews.value.filter(r => r.score === 3).length;
        reviewStats.value.badCount = reviews.value.filter(r => r.score < 3).length;
        
        // 计算平均分
        if (reviews.value.length > 0) {
          const totalScore = reviews.value.reduce((sum, r) => sum + r.score, 0);
          reviewStats.value.averageScore = Number((totalScore / reviews.value.length).toFixed(1));
        } else {
          reviewStats.value.averageScore = defaultRating;
        }
      }
    } catch (error) {
      console.error('加载评价失败:', error);
    }
  };

  return {
    reviews,
    reviewStats,
    loadReviews
  };
}